from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from myadmin import models
# Create your views here.
# 图书商城前台
def index(request):
    # 获取首页的分类列表
    b = models.Books.objects.all()[8:16]
    # 获取首页中所有的图书列表
    bs= models.Books.objects.all()
    # 分配数据
    context = {'booktypes':gettypes(),'book':bs,'books':b}
    return render(request,'myhome/index.html',context)

# 前台列表页面
def booklist(request,tid):
    # 获取当前分类对象
    t = models.booktype.objects.get(id = tid)
    if t.pid == 0:
        # 获取当前顶级分类下的所有子类
        t.sub = models.booktype.objects.filter(pid=t.id)
        t.parent = t.name
    else: # 如果当前传递的分类对象是子类
        t.sub = models.booktype.objects.filter(pid = t.pid)
        parent = models.booktype.objects.get(id = t.pid)
        t.parent = parent.name
    ts = models.Books.objects.filter()[6:9]
    # 分配数据
    context = {'booktypes':gettypes(),'data':t ,'datas':ts}
    # 加载模板
    return render(request,'myhome/list.html',context)

# 前台详情页面
def detail(request,pid):
    # 获取当前分类对象
    t = models.Books.objects.get(id = pid)
    s = models.BookImgs.objects.get(id = pid)
    title = t.title
    price = t.price
    tuijian = t.tuijian
    img_url = s.img_url
    num = t.num
    author = t.author
    publisher = t.publisher
    isbn = t.isbn
    pub_date = t.pub_date

    # 分配数据
    bs= models.Books.objects.filter()[:8]

    # 加载模板
    return render(request,'myhome/detail.html', locals())

def gettypes():
    # 获取首页的分类列表
    ts = models.booktype.objects.filter(pid=0)
    for x in ts:
        x.sub = models.booktype.objects.filter(pid=x.id)
    return ts

